<script>
import {createDuel, duelDetail, duelList, getMyPokeList, joinDuel} from "@/axios/request/index.js"
import {ElMessage} from "element-plus";
import {watch} from "vue";

const groupId = localStorage.getItem("groupId")
const userId = localStorage.getItem("userId")

export default {
  data() {
    return {
      duelId: null,
      ws: null,
      messageList: [],
      duelDetailList: [],
    }
  },
  created() {
    this.duelId = this.$route.params.duelId
    let url = "ws://localhost:9002/duelWebSocket/" + this.duelId + "/" + groupId + "/" + userId
    this.ws = new WebSocket(url);
    this.ws.onopen = () => {
    }
    this.ws.onmessage = (event) => {
      this.messageList.push(event.data)
    }
    this.duelDetail(this.duelId)
  },
  beforeUnmount() {
    // 离开对决聊天室页面关闭websocket
    this.ws.close()
  },
  methods: {
    duelDetail(duelId) {
      duelDetail(duelId).then((result) => {
        this.duelDetailList = result
      })
    }
  },
  watch: {
    duelDetailList(newList, oldList) {
      const duelDetailScrollbarRef = this.$refs.duelDetailScrollbarRef
      if (duelDetailScrollbarRef) {
        this.$nextTick(() => {
          duelDetailScrollbarRef.setScrollTop(30 * newList.length - 1)
        })
      }
    }
  }
}
</script>

<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right title">
      <el-breadcrumb-item :to="{ path: '/' }" style="font-size:15px;">首页</el-breadcrumb-item>
      <el-breadcrumb-item style="font-size:15px;">poke对决</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/duel' }" style="font-size:15px;">对决列表</el-breadcrumb-item>
      <el-breadcrumb-item style="font-size:15px;">对决聊天室</el-breadcrumb-item>
    </el-breadcrumb>
  </div>
  <el-row justify="center">
    <el-col :span="12">
      <div style="border: black 2px solid; width: 99%;height: 200px;margin-top: 5px;">
        <el-scrollbar>
          <div v-for="message in this.messageList" style="height: 20px;padding: 5px;">
            <el-tag>{{ message }}</el-tag>
          </div>
        </el-scrollbar>
      </div>
    </el-col>
    <el-col :span="12">
      <div style="border: black 2px solid; width: 99%;height: 200px;margin-top: 5px;">
        <el-scrollbar ref="duelDetailScrollbarRef">
          <div v-for="duelDetail in this.duelDetailList" style="height: 20px;padding: 5px;">
            <el-tag>{{ duelDetail.content }}</el-tag>
          </div>
        </el-scrollbar>
      </div>
    </el-col>
  </el-row>
</template>

<style scoped>
</style>